/* 
 * operate module js for admin
 * include edit add and delete
 * @author luweijun
 */
(function($,_){
    var Operate = function(){
        
    };
    Operate.init = function() {
        this.initEvents();
    };
    Operate.initEvents = function() {
        this.listenDelete();
        this.listenSubmit();
        this.listenUpload();
        this.listenThumb();
    };
    Operate.showSuccess = function(msg) {
        alertify.set({ delay: 3000 });
        alertify.success(msg);
    };
    Operate.showFailed = function(msg) {
         alertify.set({ delay: 3000 });
         alertify.log(msg);
    };
    Operate.showError = function(msg) {
        alertify.set({ delay: 3000 });
        alertify.error(msg);
    };
    Operate.listenDelete = function(e) {
        var _this = this;
        $("table.footable").delegate("a.del","click",function(event){
	    var me = this;
            // confirm dialog
            alertify.confirm("确认要删除该条记录？", function (e) {
                if (e) {
                    // user clicked "ok"
                    var delUrl = $(me).attr("href");
                    _this.doDelete(delUrl,{},$(me));
                } else {
                    // user clicked "cancel"
                }
            });
	   event.preventDefault();
	   return false;
        });
    };
    Operate.doDelete = function(delUrl,para,me) {
            var _this = this;
            var params = para || {};
            params['t'] = new Date().getTime();
            $.ajax({
              type: "POST",
              url: delUrl,
              data: params,
              success: function(data){
                  if (data['state'] && data['state']) {
                     _this.showSuccess("删除成功!");
                     if (me.closest("tr").siblings().length <= 1) {
                         location.reload();
                     }
                     me.closest("tr").remove();
                  } else {
                      _this.showFailed("删除失败，请重试！");
                  }
                  return false;
              },
              error : function(data) {
                  _this.showError("遇到错误，请稍后再试!");
                  return false;
              },
              dataType: 'json'
            });
    };

    Operate.listenSubmit = function() {
        var _this = this;
        $("#jvForm").submit(function(e){
            var params = {};
            var saveUrl = $(this).attr("action");
            var hasError = false;
            if (saveUrl == '') {
                saveUrl = location.href;
                var pos = saveUrl.indexOf('?');
                if (pos != -1) {
                    saveUrl = saveUrl.substr(0,pos)
                }
            }
            $(this).find("input").each(function(index,element){
                var type = $(element).attr("type");
                if (type == 'text' || type == 'password' || type=='radio' || type=='hidden') {
                    var name = $(element).attr("name");
                    var value = $("input[name="+name+"]").val();
                    if (value == '') {
                        _this.showError("请填写完整后在提交！");
                        hasError = true;
                        return false;
                    } else {
                        params[name] = value;
                    }
                }
            });
			$(this).find("textarea").each(function(index,element){
                    var name = $(element).attr("name");
                    //var value = $("textarea[name="+name+"]").val();
					var value = window.ckeditor.document.getBody().getHtml();
                    if (value == '') {
                        _this.showError("请填写完整后在提交！");
                        hasError = true;
                        return false;
                    } else {
                        params[name] = value;
                    }
            });

            if (!hasError) {
                _this.doSave(saveUrl,params);
            }
            e.preventDefault();
            return false;
        });
        
        Operate.doSave = function(saveUrl,params) {
            var _this = this;
            params['t'] = new Date().getTime();
            $.ajax({
              type: "POST",
              url: saveUrl,
              data: params,
              success: function(data){
                  if (data['state'] && data['state']) {
                      _this.showSuccess("操作成功！");
		      setTimeout(function(){
		          location.reload();
		      },3000);
                  } else {
                      _this.showFailed("操作失败，请稍后再试!");
                  }
                  return false;
              },
              error : function(data) {
                  _this.showError("出现错误,请稍后再试!");
                  return false;
              },
              dataType: 'json'
            });
        };
        
        Operate.fileUpload = function(uploadId,okfn,errorfn){
			var uploadFileId = uploadId;
			$.ajaxFileUpload({
					url:'/admin/video/upload',
					secureuri:false,
					fileElementId:uploadFileId,
					dataType: 'json',
					success: function (data, status){
						if(typeof(data.error) != 'undefined'){
							errorfn(data);
						} else{
							okfn(data);
						}
					},
					error: function (data, status, e){
						data = {error:"请选择上传图片！"};
						errorfn(data);
					}
				});
			return false;
		};
		
		Operate.listenUpload = function() {
			var _this = this;
			$("#upload-image").click(function(){
				var errorfn = function(data) {
					if(data.error != ''){
						$("#upload-error").text(data.error);
					} else {
						$("#upload-error").text("上传失败，请稍候再试！");
					}
				};
				var okfn = function(data) {
					var res = data;
					var imgUrl = res.savepath+'/'+res.savename;
					$("#picture").val(imgUrl);
					$("#preImg").attr("src",imgUrl);
					$("#preImg").removeAttr("width").removeAttr("height");
					$("#upload-error").text("上传成功，可继续调整图片尺寸！当前图片尺寸：宽是:"+res.width+"像素"+",高是:"+res.height+"像素。");
					$("#img-width").val(res.width);
					$("#img-height").val(res.height);
					$("#zoomWidth").val(res.width);
					$("#zoomHeight").val(res.height);
				};
				_this.fileUpload('uploadFile',okfn,errorfn);
			});
		};
                
                Operate.performThumb = function(orig,width,height,okfn,errorfn) {
			var param = {'orig':orig,'width':width,'height':height,'t':new Date().getTime()};
			$.post("/admin/video/thumb", param, function(data){
				var res = $.parseJSON(data);
				if (res.error) {
					errrorfun(res);
				} else {
					okfn(res);
				}
			});
		},
		
		Operate.listenThumb = function() {
			var _this = this;
			$("#thumb-image").click(function(){
				var orig = $("#preImg").attr("src");
				var width = $("#zoomWidth").val().trim();
				var height = $("#zoomHeight").val().trim();
				var errorfn = function(res) {
					$("#cut-error").text(res.error);
				};
				var okfn = function(res) {
					$("#preImg").attr("src",res.newName);
					$("#picture").val(res.newName);
					$("#zoomWidth").val(res.width);
					$("#zoomHeight").val(res.height);
				};
				_this.performThumb(orig,width,height,okfn,errorfn);
			});
		};

		Operate.initCategoryEvent = function() {
			$(".ums-category").delegate('.ums-cat select','change',function(){
					var _this = this;
					var cid = $(this).find("option:selected").val();
					$(this).parent().nextAll('.ums-cat').remove();
					$(this).parent().nextAll('.error').text('');
					if (cid != '') {
						$("#category_id").val(cid);
						$.post("/category/deal/nextlevel", {pid:cid,t:new Date().getTime()}, function(data){
							var res = data;
							if (typeof res == 'object' && res.length>0) {
								var html = [];
								html.push('<span class="ums-cat">');
								html.push('<select name="super" id="top-cat" class="cat-select">');
								html.push('<option value="">请选择分类</option>');
								for (var i=0,len=res.length; i<len; i++) {
									html.push('<option value="'+ res[i].id +'" index='+res[i].id+'>'+res[i].name+'</option>');
								}
								html.push('</select></span>');
								$(html.join('')).insertAfter($(_this).closest('.ums-cat'));
							} else {
								$(".ums-category .error").text('没有下一级分类了');
							}
						});
					}
			});

		};
        
    };
    umams.admin.Operate = Operate;
})(jQuery,_);


(function($,_){

    var test = function(){
        
    };
    test.init = function() {
        this.initEvents();
    };
    test.initEvents = function() {
        $(".").click(function(){
            $.ajax({
              type: "POST",
              url: delUrl,
              data: params,
              success: function(data){
                  if (data['state'] && data['state']) {
                     _this.showSuccess("删除成功!");
                     if (me.closest("tr").siblings().length <= 1) {
                         location.reload();
                     }
                     me.closest("tr").remove();
                  } else {
                      _this.showFailed("删除失败，请重试！");
                  }
                  return false;
              },
              error : function(data) {
                  _this.showError("遇到错误，请稍后再试!");
                  return false;
              },
              dataType: 'json'
            });
			});

			}

    umams.admin.Test = test;
})(jQuery,_);



$(document).ready(function(){
    umams.admin.Operate.init();
    umams.admin.Test.init();
});


